package perform.utilities;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import perform.exception.ConfigurationException;
import perform.type.Type;

public class Configuration {
	
	private Properties properties;
	private List<Class<? extends Type>> classes;
	
	@SuppressWarnings({ "unchecked" })
	public Configuration() throws ConfigurationException{
		try {
			File file = new File("configuration" + System.getProperty("file.separator") + "perform-config.xml");
			SAXReader reader = new SAXReader();
			Document document = reader.read(file);
			Element root = document.getRootElement();
			
			properties = new Properties();
			classes = new ArrayList<Class<? extends Type>>();
			properties.put("host", "127.0.0.1");
			properties.put("port", "3306");
			properties.put("username", "root");
			properties.put("password", "");
			properties.put("min-pool-size", "10");
			properties.put("acquire-increment", "5");
			properties.put("max-pool-size", "20");
			properties.put("drop", "true");
			properties.put("writeSQL", "false");
			properties.put("charset", "utf8");
			properties.put("collation", "utf8_bin");
			
			putElements(root.elements());
		} catch (DocumentException e) {
			throw new ConfigurationException("Error while parsing 'perform-config.xml' document.", e);
		} catch (ClassNotFoundException e) {
			throw new ConfigurationException("Wrong value for <classs> element in 'perform-config.xml' document.", e);
		} catch (Exception e){
			throw new ConfigurationException(e);
		}
	}
	
	@SuppressWarnings("unchecked")
	private void putElements(List<Element> elements) throws ClassNotFoundException{
		for(int i = 0; i < elements.size(); i++){
			if(elements.get(i).getName().equals("database")){
				putElements(elements.get(i).elements());
			} else if(elements.get(i).getName().equals("classes")){
				putClasses(elements.get(i).elements());
			} else {
				properties.put(elements.get(i).getName(), elements.get(i).getText());
			}
		}
	}
	@SuppressWarnings("unchecked")
	public void putClasses(List<Element> elements) throws ClassNotFoundException{
		for(int i = 0; i < elements.size(); i++){
			classes.add((Class<? extends Type>) Class.forName(elements.get(i).getText()));
		}
	}
	
	public Properties getProperties() {
		return properties;
	}
	public void setProperties(Properties properties) {
		this.properties.putAll(properties);
	}
	public List<Class<? extends Type>> getClasses() {
		return classes;
	}
	public void setClasses(List<Class<? extends Type>> classes) {
		this.classes = classes;
	}
	public String getProperty(String key){
		return properties.getProperty(key);
	}
	
}
